package com.apex.shared.starter.exception;

import com.apex.shared.starter.constant.HttpStatusCode;
import com.apex.shared.starter.core.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 全局异常处理器
 *
 * @author MoNaiHui
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public Result<?> handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error("业务异常：{}，请求地址：{}", e.getMessage(), request.getRequestURI(), e);
        return Result.fail(e.getCode(), e.getMessage());
    }

    /**
     * 处理 SpringMVC 参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public Result<?> handleBindException(BindException e, HttpServletRequest request) {
        log.error("参数绑定异常，请求地址：{}", request.getRequestURI(), e);
        String message = extractBindingErrorMessage(e.getBindingResult());
        return Result.fail(HttpStatusCode.BAD_REQUEST, message);
    }

    /**
     * 处理 SpringMVC 参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        log.error("参数校验异常，请求地址：{}", request.getRequestURI(), e);
        String message = extractBindingErrorMessage(e.getBindingResult());
        return Result.fail(HttpStatusCode.BAD_REQUEST, message);
    }

    /**
     * 处理 SpringMVC 约束违反异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<?> handleConstraintViolationException(ConstraintViolationException e, HttpServletRequest request) {
        log.error("约束违反异常，请求地址：{}", request.getRequestURI(), e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        List<String> errorMessages = new ArrayList<>();
        for (ConstraintViolation<?> violation : violations) {
            errorMessages.add(violation.getMessage());
        }
        return Result.fail(HttpStatusCode.BAD_REQUEST, String.join("; ", errorMessages));
    }

    /**
     * 处理 SpringMVC 请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        log.error("请求方法不支持，请求地址：{}", request.getRequestURI(), e);
        return Result.fail(HttpStatusCode.METHOD_NOT_ALLOWED, String.format("请求方法不支持: %s", e.getMessage()));
    }

    /**
     * 处理 SpringMVC 媒体类型不支持异常
     */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Result<?> handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e, HttpServletRequest request) {
        log.error("媒体类型不支持，请求地址：{}", request.getRequestURI(), e);
        return Result.fail(HttpStatusCode.UNSUPPORTED_MEDIA_TYPE, String.format("媒体类型不支持: %s", e.getMessage()));
    }

    /**
     * 处理其他 SpringMVC 相关异常
     */
    @ExceptionHandler({
            NoHandlerFoundException.class,
            HttpMediaTypeNotAcceptableException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            ServletRequestBindingException.class,
            ConversionNotSupportedException.class,
            MissingServletRequestPartException.class,
            AsyncRequestTimeoutException.class
    })
    public Result<?> handleSpringMvcException(Exception e, HttpServletRequest request) {
        log.error("SpringMVC异常，请求地址：{}", request.getRequestURI(), e);
        return Result.fail(HttpStatusCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }

    /**
     * 处理所有未知异常
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e, HttpServletRequest request) {
        log.error("系统异常，请求地址：{}", request.getRequestURI(), e);
        return Result.fail(HttpStatusCode.INTERNAL_SERVER_ERROR, "系统繁忙，请稍后重试");
    }

    /**
     * 提取绑定错误信息
     */
    private String extractBindingErrorMessage(BindingResult bindingResult) {
        List<String> errorMessages = new ArrayList<>();
        for (FieldError error : bindingResult.getFieldErrors()) {
            errorMessages.add(String.format("%s: %s", error.getField(), error.getDefaultMessage()));
        }
        return String.join("; ", errorMessages);
    }
} 